
package com.platform.modules.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.utils.Constant;
import com.platform.common.utils.Md5Utils;
import com.platform.common.utils.Query;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.dao.MallWhitelistDao;
import com.platform.modules.mall.entity.MallActivityEntity;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.entity.MallWhitelistEntity;
import com.platform.modules.mall.service.MallUserService;
import com.platform.modules.mall.service.MallWhitelistService;
import com.platform.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Service实现类
 *
 * @author
 * @date 2020-09-23 11:17:25
 */
@Service("mallWhitelistService")
public class MallWhitelistServiceImpl extends ServiceImpl<MallWhitelistDao, MallWhitelistEntity> implements MallWhitelistService {
    @Autowired
    private MallUserService userService;
    @Autowired
    SysConfigService sysConfigService;

    @Override
    public List<MallWhitelistEntity> queryAll(Map<String, Object> params) {
        setQueryIsMd5(params);
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        setQueryIsMd5(params);
        //排序
        params.put("sidx", "T.ADD_TIME");
        params.put("asc", false);
        Page<MallWhitelistEntity> page = new Query<MallWhitelistEntity>(params).getPage();
        return page.setRecords(baseMapper.selectMallWhitelistPage(page, params));
    }

    private void setQueryIsMd5(Map<String, Object> params) {
        String isMd5= sysConfigService.getValue("WHITELIST_MD5");
        if(Constant.STR_ONE.equals(isMd5)){
            String phone= (String) params.get("phone");
            String idCard= (String) params.get("idCard");
            params.put("phone",StringUtils.isEmpty(phone)?null:Md5Utils.encrypt(phone));
            params.put("idCard",StringUtils.isEmpty(idCard)?null:Md5Utils.encrypt(idCard));
        }
    }

    @Override
    public boolean add(MallWhitelistEntity mallWhitelist) {
        String isMd5= sysConfigService.getValue("WHITELIST_MD5");
        if(Constant.STR_ONE.equals(isMd5)){
            mallWhitelist.setPhone(StringUtils.isEmpty(mallWhitelist.getPhone())?"0":Md5Utils.encrypt(mallWhitelist.getPhone()));
            mallWhitelist.setIdCard(StringUtils.isEmpty(mallWhitelist.getIdCard())?"0":Md5Utils.encrypt(mallWhitelist.getIdCard()));
        }
        return this.save(mallWhitelist);
    }

    @Override
    public boolean addByUserId(String userId, Integer type) {
        MallUserEntity userEntity = userService.getById(userId);
        if (userEntity == null || StringUtils.isBlank(userEntity.getMobile()) || type == null) {
            return false;
        }
        // 用户付款成功添加抽奖次数,根据用户发货的手机号码绑定

        String isMd5= sysConfigService.getValue("WHITELIST_MD5");
        MallWhitelistEntity mallWhitelistEntity = this.getOne(new LambdaQueryWrapper<MallWhitelistEntity>()
                .eq(MallWhitelistEntity::getPhone, Constant.STR_ONE.equals(isMd5)? Md5Utils.encrypt(userEntity.getMobile()):userEntity.getMobile())
                .eq(MallWhitelistEntity::getType, type));
        List<MallWhitelistEntity> list = this.list(new LambdaQueryWrapper<MallWhitelistEntity>().eq(MallWhitelistEntity::getType, type));
        if (list != null && list.size() >= 300) {
            return true;
        }
        if (mallWhitelistEntity == null) {
            mallWhitelistEntity = new MallWhitelistEntity();
            mallWhitelistEntity.setNumber(1);
            mallWhitelistEntity.setPhone(userEntity.getMobile());
            mallWhitelistEntity.setType(type);
            this.save(mallWhitelistEntity);
        }
        return true;
    }

    @Override
    public boolean update(MallWhitelistEntity mallWhitelist) {
        MallWhitelistEntity whitelist=this.getById(mallWhitelist.getId());
        String isMd5= sysConfigService.getValue("WHITELIST_MD5");
        if(Constant.STR_ONE.equals(isMd5)){
            if(!whitelist.getIdCard().equals(mallWhitelist.getIdCard())){
                mallWhitelist.setIdCard(Md5Utils.encrypt(mallWhitelist.getIdCard()));
            }
            if(!whitelist.getPhone().equals(mallWhitelist.getPhone())){
                mallWhitelist.setPhone(Md5Utils.encrypt(mallWhitelist.getPhone()));
            }
        }

        return this.updateById(mallWhitelist);
    }


    @Override
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public boolean isValidByPhone(String phone, int type) {
        String isMd5= sysConfigService.getValue("WHITELIST_MD5");
        return Optional.ofNullable(
                this.lambdaQuery()
                        .eq(MallWhitelistEntity::getPhone, Constant.STR_ONE.equals(isMd5)? Md5Utils.encrypt(phone):phone)
                        .eq(MallWhitelistEntity::getValid, 1)
                        .eq(MallWhitelistEntity::getType, type)
                        .one()
        ).map(x -> x.getValid() == 1)
                .orElse(false);
    }

    @Override
    public boolean reduceByPhone(String phone, int num, int type) {
        String isMd5= sysConfigService.getValue("WHITELIST_MD5");
        return this.update(new UpdateWrapper<MallWhitelistEntity>()
                .setSql("number = number - " + num)
                .eq("phone", Constant.STR_ONE.equals(isMd5)? Md5Utils.encrypt(phone):phone)
                .ge("number", num)
                .eq("valid", 1)
                .eq("type", type));
    }
    @Override
    public MallWhitelistEntity selectWhitelistEntity(String mobile, int whitelistType) {
        String isMd5= sysConfigService.getValue("WHITELIST_MD5");
        MallWhitelistEntity entity = this.lambdaQuery()
                .eq(MallWhitelistEntity::getValid, Constant.ONE)
                .ge(MallWhitelistEntity::getNumber, 1)
                .eq(MallWhitelistEntity::getPhone, Constant.STR_ONE.equals(isMd5)? Md5Utils.encrypt(mobile): mobile)
                .eq(MallWhitelistEntity::getType, whitelistType)
                .orderByAsc(MallWhitelistEntity::getLapseTime)
                .last(" LIMIT 1")
                .one();
        return entity;
    }

    @Override
    public List<MallWhitelistEntity> selectWhiteListByPhone(String phone, int whitelistType) {
        List<MallWhitelistEntity> list = this.lambdaQuery()
                .eq(MallWhitelistEntity::getValid, Constant.ONE)
                .eq(MallWhitelistEntity::getPhone,phone)
                .eq(MallWhitelistEntity::getType, whitelistType)
                .orderByAsc(MallWhitelistEntity::getLapseTime)
                .list();
        return list;
    }
}
